package com.idea.rdftree.editor;

import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.syntax.jedit.JEditTextArea;

import com.hp.hpl.jena.rdf.model.Model;
import com.idea.io.RdfIOKit;

public abstract class SourcePanel extends JPanel  implements ChangeListener{

	protected JScrollPane scroll;
	private Model model;
	private JButton refreshButton;
	String base = "http://ideagraph.net/base";

	public SourcePanel() {
		super();
	}

	// abstract JEditTextArea getTextArea();

	abstract void attachHighlighter(JEditTextArea textArea);

	abstract String getSyntax();

	abstract String getLabel();

	abstract String getText();

	abstract void setCaretPosition(int position);

	abstract void setText(String text) ;
	
	public void setModel(Model model) {
		this.model = model;
	}

	/*
	 * public void stateChanged(ChangeEvent event) {
	 * parentListener.stateChanged(event); System.out.println("STATECHANGED IN
	 * TURTLE SOURCE PANE"); System.out.println(event.getSource()); }
	 */

	/*
	 * 
	 * public void actionPerformed(ActionEvent event) {
	 * System.out.println("ACTIONPERFORMED IN TURTLE SOURCE PANE");
	 * System.out.println(event.getSource()); if
	 * (event.getSource().equals(refreshButton)) {
	 * System.out.println("REFRESHING!!"); refreshFromText(); }
	 * parentListener.stateChanged(null); }
	 * 
	 */

	public void refreshFromText() {
		Model modelCopy = model; // er - that'll be a pointer?
		String text = getText();
		try {
			model = RdfIOKit.stringToModel(text, base, getSyntax());
		} catch (Exception exception) {
			exception.printStackTrace();
			model = modelCopy;
			refreshFromModel();
		}
	}
	
	// called when tabs clicked
	public void stateChanged(ChangeEvent e) {
		// System.out.println("Change "+e);
		Component c = ((JTabbedPane)e.getSource()).getSelectedComponent();
		// System.out.println(c);
		if (this == c) {
		//	System.out.println("refreshing "+c);	
		refreshFromModel();
		repaint();
		}
		
	}
	
	public void refreshFromModel() {
		System.out.println("SYNTAX " + getSyntax());
		setText(RdfIOKit.modelToString(model, getSyntax()));
		setCaretPosition(0); // scroll to top
	}



	public JButton getRefreshButton() {
		return refreshButton;
	}

}